package com.rykj.energy.database.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rykj.energy.common.enums.DeviceTypes;
import com.rykj.energy.common.enums.ExceptionCode;
import com.rykj.energy.common.enums.StateType;
import com.rykj.energy.common.utils.CollectionUtils;
import com.rykj.energy.common.utils.Result;
import com.rykj.energy.common.utils.StringUtils;
import com.rykj.energy.database.mapper.DeviceMapper;
import com.rykj.energy.database.pojo.BasicCamera;
import com.rykj.energy.database.pojo.BasicCameraPresetting;
import com.rykj.energy.database.pojo.BasicDevice;
import com.rykj.energy.database.pojo.vo.DeviceVo;
import com.rykj.energy.database.pojo.vo.OrganizationVO;
import com.rykj.energy.database.pojo.vo.VBasicCameraView;
import com.rykj.energy.database.service.ICameraPresettingService;
import com.rykj.energy.database.service.ICameraService;
import com.rykj.energy.database.service.IDeviceSercive;
import com.rykj.energy.database.service.IOrganizationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service("deviceSercive")
@Slf4j
public class DeviceSerciveImpl implements IDeviceSercive {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private ICameraService cameraService;

    @Autowired
    private IOrganizationService orgService;

    @Autowired
    private ICameraPresettingService cameraPresettingService;

    @Override
    public void getVoToDevice(DeviceVo deviceVo, BasicDevice device) {
        BeanUtils.copyProperties(deviceVo,device);
    }

    @Override
    public Result checkDevice(BasicDevice device) {
        if(!StringUtils.isIP(device.getDevIp())){
            return Result.failure( ExceptionCode.DATA_ERROR.getMessage()+":"+device.getDevIp());
        }
        List<BasicDevice> devices = new ArrayList<>();
        //验证名称唯一
        if(StringUtils.isNotEmpty(device.getDevAlias())){
            devices = findByDevAlias(device.getDevAlias());
            if(CollectionUtils.isNotEmpty(devices)&&
                    (device.getId()<1 || devices.size()>1|| !(devices.get(0).getId()+"").equals(device.getId()+""))){
                return Result.failure( ExceptionCode.CAMERA_NAME_IS_EXISTENCE.getMessage());
            }
        }
        devices = findByDevIp(device.getDevIp());
        if(CollectionUtils.isNotEmpty(devices)&&
                (device.getId()<1 || devices.size()>1|| !(devices.get(0).getId()+"").equals(device.getId()+""))){
            return Result.failure(ExceptionCode.CAMERA_IS_EXISTENCE.getMessage());
        }
        return  Result.success("校验通过");
    }

    @Override
    public  List<BasicCamera> addDevice(BasicDevice device) throws Exception {
        device.setCreateTime(new Date());
        device.setDevStatus(StateType.NORMAL.getCode());
        device.setLineStatus(StateType.NORMAL.getCode());
        List<BasicCamera> cameras =  queryCameraForNVR(device);
        //如果nvr下有摄像头 才保存设备信息
        if(cameras!=null&&cameras.size()>0){
            deviceMapper.insert(device);
            for (BasicCamera camera:cameras){
                camera.setDevId(device.getId());
            }
        }else{
            throw new Exception("nvr下摄像头获取失败");
        }
        return cameras;
    }

    @Override
    public List<BasicCamera> queryCameraForNVR(BasicDevice device) {
        Integer orgId =device.getOrgId();
        List<BasicCamera> cameras = new ArrayList<>();
        // cameras=  CameraClientServer.listCamera(camera, SysConfig.getCsClient());
        // List<BasicCamera> cameras = new ArrayList<>();
        List<BasicCamera> retCameras = new ArrayList<>();
        if(CollectionUtils.isEmpty(cameras)) {
            return cameras;
        }
       /*  String img = null;
       for (BasicCamera ca : cas){
            try{
                ResultDto<String> resultDto = CameraClientServer.getCameraImg(ca, SysConfig.getCsClient());
                if(resultDto.isResultStatus()){
                    resultDto = fileServer.getPhotoPath(resultDto.getResultValue(),null,"/"+ FileType.cameraImg.getValue());
                    log.info("==nvr下摄像头"+ca.getChannelAlias()+"下载图片结果===:"  + JSONObject.toJSONString(resultDto));
                    if(resultDto.isResultStatus() && !"null".equals(resultDto.getResultValue())){
                        img = resultDto.getResultValue();
                        if(StringUtils.isNotEmpty(img)){
                            ca.setParentNVRId(camera.getChannelId()+"");
                            ca.setPhotoPath(img);
                            ca.setLineStatus("normal");
                        }else {
                            ca.setLineStatus("offline");
                        }
                    }
                }else {
                    ca.setLineStatus("offLine");
                    log.error("==nvr下摄像头"+ca.getChannelAlias()+"抓取现场图片结果===:"  + JSONObject.toJSONString(resultDto));
                }
            }catch (Exception e){
                log.error("===计算端连接异常==",e);
                throw new Exception("计算端连接异常,请检查计算端是否正常启动;");
            }
            cameras.add(ca);
        }*/

        //剔除已添加的摄像头--根据IP、通道号去重
        List<BasicCamera> list = cameraService.findByIp(device.getDevIp());
        if(CollectionUtils.isNotEmpty(list)){
            for (int i=0;i<cameras.size();i++){
                Boolean b = false;
                BasicCamera ca =cameras.get(i);
                for (int j=0;j<list.size();j++){
                    BasicCamera c =list.get(j);
                    if(ca.getCamIndex().equals(c.getCamIndex())){
                        b = true;  //已添加
                        break;
                    }
                }
                if(!b){   //未添加
                    if(orgId!=null && orgId!=0){
                        ca.setOrgId(orgId);
                    }
                    retCameras.add(ca);
                }
            }
        }else {
            retCameras = cameras;
        }
        return retCameras;
    }


    @Override
    public List<BasicDevice> findByDevAlias(String devAlias) {
        Map<String,Object> cloumMap =new HashMap<>();
        cloumMap.put("devStatus",StateType.NORMAL.getCode());
        cloumMap.put("devAlias",devAlias);
        return  deviceMapper.selectByMap(cloumMap);
    }

    @Override
    public List<BasicDevice> findByDevIp(String devIp) {
        Map<String,Object> cloumMap =new HashMap<>();
        cloumMap.put("devStatus",StateType.NORMAL.getCode());
        cloumMap.put("devIp",devIp);
        return  deviceMapper.selectByMap(cloumMap);
    }

    @Override
    public void deleteDevCamera(int devId) throws Exception {
        try{
            BasicDevice device =deviceMapper.selectById(devId);
            device.setDevStatus(StateType.DELETED.getCode());
            deviceMapper.updateById(device);
            cameraService.deleteByDevId(devId);
        }catch (Exception e){
            log.error("===删除设备和摄像头异常===",e);
            throw new Exception("删除设备和摄像头异常");
        }
    }

    @Override
    public List<BasicCamera> updateDevice(BasicDevice device) throws Exception {

        BasicDevice deviceInfo = deviceMapper.selectById(device.getId());
        BeanUtils.copyProperties(device,deviceInfo);
        deviceMapper.updateById(deviceInfo);

        List<BasicCamera> cameras =  queryCameraForNVR(deviceInfo);
        if(cameras!=null&&cameras.size()>0){
            for (BasicCamera camera:cameras){
                camera.setDevId(deviceInfo.getId());
            }
        }else{
           throw new Exception("修改摄像头，nvr下摄像头获取失败");
        }
        return  cameras;
    }

    @Override
    public IPage<DeviceVo> getCamerasByOrgId(Integer pageNum, Integer pageSize, Integer orgId, String searchName, String searchIp, String devType) {
        List<Integer> orgIds =new ArrayList<>();
        if(StringUtils.isNotEmpty(orgId)){
            orgIds= orgService.getChildOrgIdsById(orgId);
            orgIds.add(orgId);
        }
        Page<DeviceVo> page=new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        IPage<DeviceVo> devCamPage = deviceMapper.getCamerasByOrgId(page, orgIds,searchName,searchIp,devType);
        List<DeviceVo> deviceVos =devCamPage.getRecords();
        return devCamPage;
    }

    @Override
    public List<OrganizationVO> getOrgCameras(Integer orgId,String searchName) {
        List<Integer> orgIds=new ArrayList<>();
        orgIds.add(orgId);
        List<OrganizationVO> orgTreeVos =orgService.getOrgTree(orgId,searchName);
        getOrgTreeCameras(orgTreeVos,searchName);
        return orgTreeVos;
    }

    @Override
    public IPage<VBasicCameraView> getCameraAndPresetByOrgId(Integer pageNum, Integer pageSize, Integer orgId, String searchName, String searchIp, String devType) {
        List<Integer> orgIds =new ArrayList<>();
        if(StringUtils.isNotEmpty(orgId)){
            orgIds= orgService.getChildOrgIdsById(orgId);
            orgIds.add(orgId);
        }
        Page<VBasicCameraView> page=new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        IPage<VBasicCameraView>  camPresetPage = deviceMapper.getCameraAndPresetByOrgId(page, orgIds,searchName,searchIp,devType);
        return camPresetPage;
    }

    @Override
    public List<BasicCameraPresetting> getPresetByCameraId(Integer cameraId) {

        return cameraPresettingService.getPresetsByDevId(cameraId);
    }

    /**
     * 回调获取区域+子区域下的摄像头
     * @param orgTreeVos
     */
    private void getOrgTreeCameras(List<OrganizationVO>  orgTreeVos,String searchName){
        for (OrganizationVO orgVo:orgTreeVos ) {
            if(CollectionUtils.isNotEmpty(orgVo.getChildren())){
                getOrgTreeCameras(orgVo.getChildren(),searchName);
            }
            List<DeviceVo> deviceVos = getDeviceAndPrests(orgVo.getId(), searchName);
            orgVo.setCameras(deviceVos);
        }
    }

    /**
     * 获取区域下的摄像头+预置位
     * @param orgId
     * @return
     */
    private   List<DeviceVo>  getDeviceAndPrests(Integer orgId,String searchName){
        List<DeviceVo> deviceVos = deviceMapper.getDeviceVoByOrgId(orgId,searchName);
        List<BasicCameraPresetting> cameraPresets =cameraPresettingService.getAllPresets();
        if(CollectionUtils.isNotEmpty(cameraPresets)&&CollectionUtils.isNotEmpty(deviceVos)) {
            for (DeviceVo dvo : deviceVos) {
                if (DeviceTypes.ptz.getCode().equals(dvo.getCamType()) || DeviceTypes.half_ptz.getCode().equals(dvo.getCamType())) {
                    //查询预置位信息
                    List<BasicCameraPresetting> presettings =new ArrayList<>();
                    for (BasicCameraPresetting cameraPreset:cameraPresets ) {
                        if ((dvo.getId()+"").equals(cameraPreset.getCameraId()+"")) {
                            presettings.add(cameraPreset);
                        }
                    }
                    // presettings = cameraPresettingService.getPresetsByDevId(dvo.getId());
                    dvo.setPresetting(presettings);
                }
            }
        }
        return  deviceVos;
    }

}
